const { pool } = require('../config/db');
const { success, error } = require('../utils/response');
const moment = require('moment');

// 借阅图书
exports.borrowBook = async (req, res, next) => {
  try {
    const { bookId, borrowDays } = req.body;
    const userId = req.userId;

    console.log('📖 借阅请求:', { bookId, borrowDays, userId });

    // 参数验证
    if (!bookId) {
      console.log('❌ 缺少图书ID参数');
      return error(res, '缺少图书ID参数', 400);
    }

    const bookIdNum = parseInt(bookId);
    if (isNaN(bookIdNum) || bookIdNum <= 0) {
      console.log('❌ 无效的图书ID:', bookId);
      return error(res, '无效的图书ID', 400);
    }

    const borrowDaysNum = borrowDays ? parseInt(borrowDays) : 30;
    if (isNaN(borrowDaysNum) || borrowDaysNum <= 0 || borrowDaysNum > 365) {
      return error(res, '无效的借阅天数', 400);
    }

    // 检查图书是否存在且有库存
    const [books] = await pool.query(
      'SELECT id, name, stock FROM books WHERE id = ? AND stock > 0',
      [bookIdNum]
    );

    if (books.length === 0) {
      return error(res, '图书不存在或库存不足', 400);
    }

    const book = books[0];

    // 检查用户借阅数量是否超过限制
    const [borrowRecords] = await pool.query(
      'SELECT COUNT(*) as count FROM borrow_records WHERE user_id = ? AND status = "borrowed"',
      [userId]
    );

    const maxBooks = parseInt(process.env.MAX_BORROW_BOOKS) || 10;
    if (borrowRecords[0].count >= maxBooks) {
      return error(res, `最多只能借阅${maxBooks}本书`, 400);
    }

    // 检查是否已经借阅过此书
    const [existingBorrow] = await pool.query(
      'SELECT id FROM borrow_records WHERE user_id = ? AND book_id = ? AND status = "borrowed"',
      [userId, bookIdNum]
    );

    if (existingBorrow.length > 0) {
      return error(res, '您已经借阅过此书', 400);
    }

    // 检查是否有预约且预约已到期的书
    const [reservations] = await pool.query(
      'SELECT id FROM reservations WHERE book_id = ? AND status = "available" ORDER BY reservation_date LIMIT 1',
      [bookIdNum]
    );

    if (reservations.length > 0) {
      return error(res, '此书已被预约，请稍后再试', 400);
    }

    // 计算借阅天数和到期日期
    const defaultDays = parseInt(process.env.MAX_BORROW_DAYS) || 30;
    const actualDays = borrowDays || defaultDays;
    const dueDate = moment().add(actualDays, 'days').format('YYYY-MM-DD HH:mm:ss');

    // 创建借阅记录
    const [result] = await pool.query(
      'INSERT INTO borrow_records (user_id, book_id, borrow_date, due_date, borrow_days, status) VALUES (?, ?, NOW(), ?, ?, ?)',
      [userId, bookIdNum, dueDate, actualDays, 'borrowed']
    );

    // 减少图书库存
    await pool.query(
      'UPDATE books SET stock = stock - 1 WHERE id = ?',
      [bookIdNum]
    );

    success(res, {
      borrowId: result.insertId,
      bookName: book.name,
      dueDate: dueDate,
      borrowDays: actualDays
    }, '借阅成功');

  } catch (err) {
    next(err);
  }
};

// 获取用户的借阅记录
exports.getBorrowRecords = async (req, res, next) => {
  try {
    const userId = req.userId;
    const { status } = req.query; // borrowed, returned, overdue

    let whereClause = 'WHERE br.user_id = ?';
    let params = [userId];

    if (status) {
      whereClause += ' AND br.status = ?';
      params.push(status);
    }

    const [records] = await pool.query(`
      SELECT
        br.id,
        br.borrow_date,
        br.due_date,
        br.return_date,
        br.status,
        br.borrow_days,
        br.renew_count,
        b.id as book_id,
        b.name as book_name,
        b.author,
        b.cover
      FROM borrow_records br
      LEFT JOIN books b ON br.book_id = b.id
      ${whereClause}
      ORDER BY br.borrow_date DESC
    `, params);

    success(res, records);
  } catch (err) {
    next(err);
  }
};

// 续借图书
exports.renewBook = async (req, res, next) => {
  try {
    const { borrowId } = req.body;
    const userId = req.userId;

    // 获取借阅记录
    const [records] = await pool.query(`
      SELECT
        br.*,
        b.name as book_name,
        brl.max_renew_times
      FROM borrow_records br
      LEFT JOIN books b ON br.book_id = b.id
      LEFT JOIN borrow_rules brl ON brl.user_type = (
        SELECT user_type FROM users WHERE id = ?
      )
      WHERE br.id = ? AND br.user_id = ? AND br.status = 'borrowed'
    `, [userId, borrowId, userId]);

    if (records.length === 0) {
      return error(res, '借阅记录不存在或无权操作', 404);
    }

    const record = records[0];
    const maxRenewTimes = parseInt(process.env.MAX_RENEW_TIMES) || 2;

    // 检查续借次数
    if (record.renew_count >= maxRenewTimes) {
      return error(res, `最多只能续借${maxRenewTimes}次`, 400);
    }

    // 检查是否有预约
    const [reservations] = await pool.query(
      'SELECT COUNT(*) as count FROM reservations WHERE book_id = ? AND status = "waiting"',
      [record.book_id]
    );

    if (reservations[0].count > 0) {
      return error(res, '此书已被预约，无法续借', 400);
    }

    // 更新借阅记录
    const newDueDate = moment(record.due_date).add(record.borrow_days, 'days').format('YYYY-MM-DD HH:mm:ss');

    await pool.query(
      'UPDATE borrow_records SET due_date = ?, renew_count = renew_count + 1 WHERE id = ?',
      [newDueDate, borrowId]
    );

    success(res, {
      newDueDate: newDueDate,
      renewCount: record.renew_count + 1,
      maxRenewTimes: maxRenewTimes
    }, '续借成功');

  } catch (err) {
    next(err);
  }
};

// 获取借阅统计
exports.getBorrowStats = async (req, res, next) => {
  try {
    const userId = req.userId;

    const [stats] = await pool.query(`
      SELECT
        COUNT(CASE WHEN status = 'borrowed' THEN 1 END) as borrowed_count,
        COUNT(CASE WHEN status = 'returned' THEN 1 END) as returned_count,
        COUNT(CASE WHEN status = 'overdue' THEN 1 END) as overdue_count,
        COUNT(*) as total_count
      FROM borrow_records
      WHERE user_id = ?
    `, [userId]);

    success(res, stats[0]);
  } catch (err) {
    next(err);
  }
};
